#include "../include/header.h"

int main(int argc, char* argv[]){
	ARGS_CHECK(argc, 1);
    int pipe_read = open("1.pipe", O_RDONLY);
	ERROR_CHECK(pipe_read, -2, "open read");
    int pipe_write = open("2.pipe", O_WRONLY);
	ERROR_CHECK(pipe_write, -1, "open write");

    fd_set set;
    FD_ZERO(&set);

	long remain = 10;
    while(1){

        FD_SET(STDIN_FILENO, &set);
        FD_SET(pipe_read, &set);


		struct timeval tv = {remain, 0};
        
		int ret_select = select(10, &set, NULL, NULL, &tv);
		if(ret_select == 0){
			printf("超时退出");
			exit(0);
		}



        if(FD_ISSET(STDIN_FILENO, &set)){
            char buf[60] = {0};
            bzero(buf, sizeof(buf));
            read(STDIN_FILENO, buf, sizeof(buf));
            write(pipe_write, buf, sizeof(buf));

			remain = 10;
        }

        if(FD_ISSET(pipe_read, &set)){
            char buf[60] = {0};
            bzero(buf, sizeof(buf));
            int res = read(pipe_read, buf, sizeof(buf));
            if(res == 0){
                printf("对端关闭了管道 \n");
                break;
            }
            printf("A: %s \n", buf);

			remain = tv.tv_sec;
        }
    }

    close(pipe_read);
    close(pipe_write);

    return 0;	
}